#include "entry.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

cconf_entry_t * 
cconf_entry_create(char * path, cconf_validator_t * val, char * doc, char * def, cconf_entry_t * par)
{
    cconf_entry_t * new = calloc(1, sizeof(cconf_entry_t));
    new->path = strdup(path);
    new->validator = val;
    new->docstring = doc ? strdup(doc) : NULL;
    new->def = def ? strdup(def) : strdup("");
    new->value = strdup(new->def);
    new->children = NULL;
    new->n_children = 0;
    
    new->parent = par;
    
    if (par != NULL)
    {
		par->children = realloc(
			par->children, (par->n_children + 1) * sizeof(cconf_entry_t *));
			
		par->children[par->n_children++] = new;
	}
    
    return new;
}

void cconf_entry_set_value(void * entry, char * value)
{
	cconf_entry_t * e = entry;
	char * v = e->value;
	
	e->value = value;
	free(v);
}

char * cconf_entry_get_value(void * entry)
{
	cconf_entry_t * e = entry;
	return e->value;
}

char * cconf_entry_document(void * entry)
{
	char * out;
	cconf_entry_t * par, * e = entry;
	
	if (NULL == e)
	{
		asprintf(&out, "no such entry");
		return out;
	}
		
	par = e;
	while (par->parent != NULL)
		par = par->parent;
		
	asprintf(&out, "%s: %s\n    %s\n    default: \"%s\"", 
            e->path, par->docstring,
            par->validator->docstring,
            e->def
    );
	
	return out;
}

void cconf_entry_free(void * entry)
{
    cconf_entry_t * e = entry;
    
    free(e->path);
    free(e->docstring);
    free(e->def);
    
    if (e->value)
		free(e->value);
    
    if (e->validator);
		cconf_validator_free(e->validator);
		
	if (e->children)
		free(e->children);
		
    free(e);
}
